/*
 * Copyright© 2013-2018 YZTC 
 * Author zhenghl 
 * 本公司保留所有下述内容的权利; 
 * 本内容为保密信息，仅限本公司内部使用; 
 * 非经本公司书面许可，任何人不得外泄或用于其他目的; 
*/
package com.wxmp.core.interceptor;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
/**
 * xss攻击防御过滤器 -csrf攻击防御过滤
* @ClassName: XSSFilter 
* @version 1.0 2018年5月30日 下午3:55:42
 */
public class XSSFilter implements Filter {
	/**   
	* 需要排除的页面   
	*/    
	private String excludedPages;  
	private String[] excludedPageArray;
	@Override
	public void destroy() {
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
		String reqUri = req.getRequestURI();
		boolean isExcludedPage = false;     
		for (String page : excludedPageArray) {//判断是否在过滤url之外    equals(page) 
			if(reqUri.indexOf(page)!=-1){     
			isExcludedPage = true;     
			break;     
			}     
		} 
		if(isExcludedPage){
			chain.doFilter(request, response);
			return;
		}
		XSSRequestWrapper xssRequest=new XSSRequestWrapper((HttpServletRequest) request);
		/**
		  * csrf防御
		  */
		/*HttpSession session = xssRequest.getSession();
		String sToken = (String)session.getAttribute("csrf_token"); 
		if(sToken == null){ 
			String csrf_token = UUID.randomUUID().toString();
			session.setAttribute("csrf_token",csrf_token); 
		} else{ 
		   String xhrToken = xssRequest.getHeader("csrf_token"); 
		   String pToken = xssRequest.getParameter("csrf_token"); 
		   if(!reqUri.contains("index.do")
				   &&!reqUri.contains("login.do")
			   			&&!reqUri.contains("loginCheck.do")){
			   if(sToken != null && xhrToken != null && sToken.equals(xhrToken)){ 
			   }else if(sToken != null && pToken != null && sToken.equals(pToken)){ 
			   }else{ 
				   resp.sendRedirect(xssRequest.getContextPath()+"/jsp/500.jsp");
				   return ;
			   } 
		   }
		}*/
		/**
		  * csrf防御-结束
		  */
		chain.doFilter(xssRequest, response);
	}
	@Override
	public void init(FilterConfig config) throws ServletException {
		 excludedPages = config.getInitParameter("excludedPages");     
		 if (StringUtils.isNotEmpty(excludedPages)) {
			 excludedPageArray = excludedPages.split(",");     
		 } 
		 return;
	}
}
